import React from 'react'
import { Link, useHistory } from 'react-router-dom'
import { useSelector, useDispatch } from 'react-redux'
import { MehFilled, DownOutlined } from '@ant-design/icons'
import { message, Menu, Dropdown } from 'antd'
import { loginOut } from '@/stores/user'
import { typeUserInfo } from '@/types/user'
import Icon from '@/components/Icon'
import './index.scss'
import { $confirm } from '@/register/globalFun'

const adminMenu = [
  { path: '/admin/user-list', label: '用户管理' },
  { path: '/admin/products-manage', label: '商品管理' },
  { path: '/admin/orders-manage', label: '订单管理' },
]

const Header = () => {
  const history = useHistory()
  const dispatch = useDispatch()
  const { userInfo }:{userInfo:typeUserInfo} = useSelector((state:any) => state.user)

  /**
   * 点击退出登录
   */
  const onclickLoginOut = () => {
    $confirm('确认退出登录?', () => {
      dispatch(loginOut())
      history.push('/')
      message.info('已退出登录')
    })
  }

  return (
    <header>
      <div className="container">
        <span
          className="title"
          onClick={() => { history.push('/') }}
        >
          大恐龙商城
        </span>

        <div className="controllers">
          <Link to="/cart-items">
            <Icon
              color="#ffffff"
              name="icon-gouwuche"
              style={{ marginRight: '4px' }}/>
              购物车
          </Link>
          {
            !userInfo
              ? (
                <Link to="/login">
                  <MehFilled style={{ marginRight: '4px' }} />登录
                </Link>
              )
              : (
                <div>
                  {/* 用户下拉列表 */}
                  <Dropdown overlay={(
                    <Menu>
                      <Menu.Item key="user-home">
                        <Link to={'/user-info'}>个人资料</Link>
                      </Menu.Item>
                      <Menu.Item key="loginout">
                        <span onClick={onclickLoginOut}>退出登录</span>
                      </Menu.Item>
                    </Menu>
                  )}
                  >
                    <span className="user-name">{userInfo.name} <DownOutlined /></span>
                  </Dropdown>
                  {
                    userInfo.isAdmin &&
                    <Dropdown overlay={(
                      <Menu>
                        {
                          adminMenu.map(item => (
                            <Menu.Item key={item.path}>
                              <Link to={item.path}>{item.label}</Link>
                            </Menu.Item>
                          ))
                        }
                      </Menu>
                    )}
                    >
                      <span className="user-name">后台管理 <DownOutlined /></span>
                    </Dropdown>
                  }
                </div>
              )
          }
        </div>
      </div>
    </header>
  )
}

export default Header
